package com.sun.study;

import com.sun.study.utils.jdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author Sun
 * @Date 2020/4/12 0:01
 * @Version 1.0
 */
public class TestTransaction {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
            con = jdbcUtils.getConnection();

            //关闭自动提交，在IDEA中相当于自动的开启事务了
            con.setAutoCommit(false);

            String sql1 = "update sc set degree = degree-16 where SNO=?";
            st = con.prepareStatement(sql1);//预编译sql
            st.setString(1, "20050101");
            st.executeUpdate();

            String sql2 = "update sc set degree = degree+5 where SNO=?";
            st = con.prepareStatement(sql2);//预编译sql
            st.setString(1, "20050201");
            st.executeUpdate();


            //提交事务，如果不执行这一步，数据将不会持久化
            con.commit();

        } catch (SQLException e) {
            try {
                //如果失败就回滚
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            jdbcUtils.Release(con, st, rs);
        }
    }
}
